#!/bin/sh
# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

SCRIPT="$(readlink -f $0)"
SCRIPT_DIR="$(dirname ${SCRIPT})/init.d"

DAEMON_NAME='chameleond'
UPDATER_NAME='chameleon-updater'
INITD_DIR='/etc/init.d'
CONFIG_FILE="/etc/default/${DAEMON_NAME}"
CHAMELEOND_DIR='/usr/bin'
DAEMON="${CHAMELEOND_DIR}/run_chameleond"

if [[ ! -x ${DAEMON} ]]; then
    echo "Executable ${DAEMON} not existed. Install it first." 1>&2
    exit 1
fi

update-rc.d -f ${DAEMON_NAME} remove
update-rc.d -f ${UPDATER_NAME} remove

CONFIG_TMP="$(mktemp /tmp/${DAEMON_NAME}.XXXXXX)"
cat <<END >${CONFIG_TMP}
CHAMELEOND_DIR="${CHAMELEOND_DIR}"
BUNDLE_VERSION="${BUNDLE_VERSION}"
CHAMELEON_BOARD="${CHAMELEON_BOARD}"
END
mv -f "${CONFIG_TMP}" "${CONFIG_FILE}"

cp -f "${SCRIPT_DIR}/${DAEMON_NAME}" "${INITD_DIR}"
update-rc.d "${DAEMON_NAME}" defaults 92 8

cp -f "${SCRIPT_DIR}/${UPDATER_NAME}" "${INITD_DIR}"
update-rc.d "${UPDATER_NAME}" defaults 90 10

FPGA_DIR="$(dirname ${SCRIPT})/../updatable/${CHAMELEON_BOARD}"
FPGA_BOOT_PART=$(fdisk -l /dev/mmcblk0 | grep 'a2  Unknown' | cut -f1 -d' ')
FPGA_FAT_PART=$(fdisk -l /dev/mmcblk0 | grep ' b  W95 FAT32' | cut -f1 -d' ')
MOUNT_DIR='/media/mmc1'

mount "${FPGA_FAT_PART}" "${MOUNT_DIR}"
for file in 'fpga.rbf' 'socfpga.dtb'; do
    if ! diff -q "${FPGA_DIR}/${file}" "${MOUNT_DIR}/${file}"; then
        echo "Updating ${file}"
        cp -f "${FPGA_DIR}/${file}" "${MOUNT_DIR}"
        need_reboot=1
    fi
done
umount "${MOUNT_DIR}"

file='boot-partition.img'
if ! diff -q "${FPGA_DIR}/${file}" "${FPGA_BOOT_PART}"; then
    echo "Updating ${file}"
    dd if="${FPGA_DIR}/${file}" of="${FPGA_BOOT_PART}" bs=512
    sync
    need_reboot=1
fi

if [[ -n "${need_reboot}" ]]; then
    echo 'Reboot the board to validate the FPGA configuration...'
    reboot
else
    "${INITD_DIR}/${DAEMON_NAME}" restart
fi
